package com.be.beadmin.project.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.ResultModel;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.project.dto.input.FileInfoDto;
import com.be.beadmin.project.dto.input.InfoAndPage;
import com.be.beadmin.project.dto.output.FileInfoEx;
import com.be.beadmin.project.entity.FileInfo;
import com.be.beadmin.project.repository.FileInfoRepository;
import com.be.beadmin.project.service.FileInfoService;
import com.be.beadmin.service.impl.MinioService;
import com.google.common.io.ByteStreams;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
* @author zmy
* @date 2023-02-15
**/

@Api(tags = {"项目管理-附件信息模块"})
@RestController
public class FileInfoController {

    @Autowired
    private  FileInfoService fileInfoService;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioService minioService;

    MinioUtil minioUtil = new MinioUtil();

    private String bucketName = "projectfile";
    private final FileInfoRepository fileInfoRepository;

    public FileInfoController(FileInfoRepository fileInfoRepository) throws Exception {
        this.fileInfoRepository = fileInfoRepository;
    }


    @ApiOperation("获取附件分页信息")
    @PostMapping(value = "/project/getFileInfoByPage")
    public ResultModel getFileInfoByPage(@RequestBody PageEntity pageEntity)  {
        return ResultModel.success(fileInfoService.getFileInfoByPage(pageEntity)) ;
    }

    @ApiOperation("指定项目ID获取附件分页信息")
    @PostMapping(value = "/project/getFileInfoByPageAndInfoId")
    public ResultModel getFileInfoByPageAndInfoId(@RequestBody InfoAndPage infoAndPage)  {
        return ResultModel.success(fileInfoService.getFileInfoByPageAndInfoId(infoAndPage)) ;
    }
    @ApiOperation("获取附件类型")
    @PostMapping("/project/getFileType")
    public ResultModel getFileType(){

        return ResultModel.success(fileInfoService.getFileType());
    }
    @ApiOperation("增加附件信息")
    @PostMapping("/project/addFileInfo")
    public ResultModel addFileInfo(@RequestBody FileInfoDto fileInfoDto){
        fileInfoService.addFileInfo(fileInfoDto);
        return ResultModel.success(ResultModel.ADD);
    }
    @ApiOperation("删除附件信息")
    @PostMapping("/project/delFileInfo")
    public ResultModel delFileInfo(@RequestBody FileInfoDto fileInfoDto){
        fileInfoService.delFileInfo(fileInfoDto.getId());
        return ResultModel.success(ResultModel.DELETE);
    }

    @ApiOperation("修改附件信息，不调用")
    @PostMapping("/project/updateFileInfo")
    public ResultModel updateFileInfo(@RequestBody FileInfoDto fileInfoDto){
        fileInfoService.updateFileInfo(fileInfoDto);
        return ResultModel.success(ResultModel.UPDATE);
    }


    @PostMapping("/project/exportFileInfo")
    public void exportFileInfo(HttpServletResponse response ,@RequestBody PageEntity pageEntity) throws IOException {
        Page<FileInfoEx> fileInfoPage = fileInfoService.getFileInfoByPage(pageEntity);
        List<FileInfoEx> fileInfoExes = fileInfoPage.getContent();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("FileInfo接口", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), FileInfoEx.class).sheet("sheet1").doWrite(fileInfoExes);
    }

    @ApiOperation("新增附件信息")
    @PostMapping("/project/uploadFileInfo")
    public ResultModel uploadFileInfo(@ApiParam(value = "文件类别",required = true) @RequestParam String category,
                                      @ApiParam(value = "附件",required = true) @RequestParam("file") MultipartFile[] multipartFiles,
                                      @ApiParam(value = "项目id",required = true) @RequestParam String infoId,
                                      @ApiParam(value = "文件名称") @RequestParam String fileName,
                                      @ApiParam(value = "备注") @RequestParam(required = false) String memo) throws Exception {

        //fileInfoService.uploadFileInfo(infoId,category,multipartFile,fileName,memo,bucketName);
        try {
            fileInfoService.uploadFileInfo(infoId,category,multipartFiles,fileName,memo,bucketName);
            return ResultModel.success(ResultModel.ADD);
        } catch (BeadminException e) {
            return ResultModel.error(-1,e.getMessage());
        } catch (Exception e) {
            return ResultModel.error(-2,e.getMessage());
        }

    }

    @ApiOperation("修改附件信息")
    @PostMapping("/project/updateFileInfo2")
    public ResultModel updateFileInfo2(@ApiParam(value = "附件id",required = true) @RequestParam String id,
                                       @ApiParam(value = "文件类别",required = true) @RequestParam String category,
                                       @ApiParam(value = "附件") @RequestParam(value = "file",required = false) MultipartFile multipartFile,
                                       @ApiParam(value = "项目id",required = true) @RequestParam String infoId,
                                       @ApiParam(value = "备注") @RequestParam(required = false) String memo) throws Exception {

        fileInfoService.updateFileInfo2(id,infoId,category,multipartFile,memo,bucketName);
        return ResultModel.success("修改附件信息成功");

    }

    @ApiOperation("判断bucket是否存在")
    @PostMapping ("/project/bucketExist")
    public ResultModel bucketExist(@ApiParam(value = "becketName")@RequestParam String bucketName) throws InvalidPortException, InvalidEndpointException {
        boolean exists = minioUtil.bucketExists(bucketName);
//        if(!exists) {
//            minioClient.makeBucket(bucketName);
//        }
        return ResultModel.success(exists);
    }


//    @ApiOperation("上传附件信息")
//    @PostMapping("/project/uploadFile")
//    public ResultModel upload(@ApiParam(value = "附件",required = true) @RequestParam("file") MultipartFile multipartFile) throws Exception {
//        //上传文件
//
//        fileInfoService.uploadFileInfo(infoId,category,multipartFile,memo,);
//        //数据库中添加信息
//
//        return ResultModel.success("添加附件成功");
//
//    }

    @ApiOperation("获取文件预览地址")
    @PostMapping("/project/getReadFile")
    public ResultModel getReadFile(@ApiParam(value = "文件名")@RequestParam String fileName) throws Exception {
        String url = minioUtil.getReadFile(bucketName, fileName);
        return ResultModel.success(url);
    }
    @ApiOperation("下载文件")
    @GetMapping("/project/downloadFile")
    public ResultModel downloadFile(@ApiParam(value = "附件id")@RequestParam String id,
                             HttpServletResponse response) throws Exception {
        //minioUtil.downloadFile(bucketName,fileName,response);
        //fileInfoService.download(bucketName,id,response);
        //System.out.println(response);
        try {

            //InputStream inputStream = fileInfoService.download(bucketName, id, response);
            FileInfo fileInfo = fileInfoRepository.findFileInfoById(id);
            //System.out.println(fileInfo.getBucketName());
            //System.out.println(fileInfo.getFileName());
            String fileName = fileInfo.getFileName();
            String newFileName = fileName.substring(0,fileName.lastIndexOf(".")) +"-"+ fileInfo.getVersion()+"."+fileInfo.getFileExtEndDate();
            String bucketName = fileInfo.getBucketName();
            InputStream inputStream = minioService.downloadOne(bucketName, newFileName);
            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-Disposition", "attachment;filename="+newFileName);
            //String fileType = fileName.substring( fileName.lastIndexOf('.')+1);
            response.addHeader("Content-Type", "text/plain;charset=utf-8");
            response.addHeader("Pragma","No-cache");
            response.addHeader("Cache-Control","No-cache");
            ServletOutputStream os = response.getOutputStream();

            ByteStreams.copy(inputStream, os);
            os.flush();
            return  ResultModel.success("下载成功");
        } catch (Exception e) {
            return ResultModel.error(99,"文件读取异常");
        }
    }

    @ApiOperation("创建bucket")
    @GetMapping("/project/createBucket")
    public ResultModel createBucket(@ApiParam(value = "bucketName")@RequestParam String bucketName) throws Exception {
        minioUtil.createBucketName(bucketName);
        return ResultModel.success("创建成功");
    }





}